<?php

namespace App\Http\Controllers\Cooperate;

use App\Helpers\Tools;
use App\Http\Controllers\ApiController;
use App\Models\Troops;
use App\Models\User;
use Illuminate\Foundation\PackageManifest;
use Illuminate\Support\Facades\Redis;

class TroopsController extends ApiController
{
    public function numberMatch()
    {
        $number = (int)request('number');
        $firendSex = request('firendSex');
        $count = request('count');

        // 判断自己是否有队伍，有的话则返回队伍
        $troopsNumber = Redis::get("user:troops:number:$number");
        $troops = Redis::get("troops:$troopsNumber");
        if ($troops) {
            $resource = [
                'troops_number' => $troopsNumber
            ];

            return Tools::setData($resource);
        }

        $firends = Redis::zrangebyscore('firends', $number, $number, 'WITHSCORES');

        // 查看是否有指定
        if ($firends) {
            foreach ($firends as $key => $val) {
                $firendNumber = $key;
                $firendFNumber = Redis::zscore('firends', $number);

                if ($firendNumber == $firendFNumber) {
                    Redis::zrem('firends', $firendNumber);
                    Redis::zrem('firends', $number);
                } else {
                    unset($firendNumber);
                }
                break;
            }
        }

        if ($firendSex != 4) {
            if ($count > 3) {
                $firends = Redis::zrange('match', 0, 5, 'WITHSCORES');
                $a = 1;
            } else if ($firendSex == 1) {
                $firends = Redis::zrangebyscore('match', 1, 1, 'WITHSCORES');
                $a = 2;
            } else if ($firendSex == 2) {
                $firends = Redis::zrangebyscore('match', 2, 2, 'WITHSCORES');
                $a = 3;
            } else if ($firendSex == 3) {
                $firends = Redis::zrange('match', 0, 5, 'WITHSCORES');
                $a = 4;
            }

            if ($firends) {
                foreach ($firends as $key => $val) {
                    if ($key != $number) {
                        $firendNumber = $key;
                        $res = Redis::setnx("isNx:$firendNumber", 'isnow');
                        $res2 = Redis::setnx("isNx:$number", 'isnow');
                        Redis::expire("isNx:$firendNumber", 10);
                        Redis::expire("isNx:$number", 10);
                        if ($res && $res2) {
                            Redis::zrem('match', $firendNumber);
                            Redis::zrem('match', $number);
                            break;
                        } else {
                            return Tools::error('锁失败');
                        }
                    } else {
                        # return Tools::error( $a . '没有匹配到2' );
                    }
                }

                if (isset($firendNumber)) {
                    $troopsNumber = Redis::get("user:troops:number:$firendNumber");
                    $isTroops = Redis::get("troops:$troopsNumber");

                    if (!$isTroops) {
                        $data = [];
                        $data['number'] = $this->sendTroopsNumber();
                        $data['user_id'] = $number;
                        $data['id'] = $this->sendTroopsId();
                        $data['cooperate_id'] = $firendNumber;
                        $data['created_at'] = date('Y-m-d H:i:s');
                        $data['updated_at'] = date('Y-m-d H:i:s');

                        $res = Redis::lpush('troops:list', serialize($data));

                        $troopsData = [];
                        $troopsData[$firendNumber] = unserialize(Redis::get('user:number:' . $firendNumber));
                        $troopsData[$number] = unserialize(Redis::get('user:number:' . $number));
                        $troopsData['troops'] = $data['number'];

                        Redis::set('troops:' . $data['number'], serialize($troopsData));
                        Redis::set('user:troops:number:' . $number, $data['number']);
                        Redis::set('user:troops:number:' . $firendNumber, $data['number']);

                        if ($res) {
                            $resource = [
                                'troops_number' => $data['number'],
                                'firend_number' => $firendNumber
                            ];

                            return Tools::setData($resource);
                        }
                    } else {
                        return Tools::error('已有队伍');
                    }
                } else {
                    return Tools::error('没有匹配到1');
                }
            }
        } else {
            if (isset($firendNumber)) {
                // 判断是否已有队伍
                $troopsNumber = Redis::get("user:troops:number:$firendNumber");
                $isTroops = Redis::get("troops:$troopsNumber");
                if ($isTroops) {
                    return Tools::error($firendNumber . '已有队伍');
                }

                $data = [];
                $data['number'] = $this->sendTroopsNumber();
                $data['user_id'] = $number;
                $data['id'] = $this->sendTroopsId();
                $data['cooperate_id'] = $firendNumber;
                $data['created_at'] = date('Y-m-d H:i:s');
                $data['updated_at'] = date('Y-m-d H:i:s');

                $res = Redis::lpush('troops:list', serialize($data));

                $troopsData = [];
                $troopsData[$firendNumber] = unserialize(Redis::get('user:number:' . $firendNumber));
                $troopsData[$number] = unserialize(Redis::get('user:number:' . $number));
                $troopsData['troops'] = $data['number'];

                Redis::set('troops:' . $data['number'], serialize($troopsData));
                Redis::set('user:troops:number:' . $number, $data['number']);
                Redis::set('user:troops:number:' . $firendNumber, $data['number']);

                if ($res) {
                    $resource = [
                        'troops_number' => $data['number'],
                        'firend_number' => $firendNumber
                    ];

                    return Tools::setData($resource);
                }
            }
        }

        return Tools::error('空');
    }

    public function info($id)
    {
        $troops = unserialize(Redis::get("troops:$id"));

        return Tools::setData($troops);
    }

    public function troopsOut($id)
    {
        $res = Troops::where('number', $id)->delete();

        if ($res) {
            Redis::del("troops:$id");

            return Tools::success();
        } else {
            return Tools::error();
        }
    }

    public function user()
    {
        $number = request('number');
        $troopsNumber = Redis::get("user:troops:number:$number");
        $troops = Redis::get("troops:$troopsNumber");
        if ($troops) {
            return Tools::success($troopsNumber);
        } else {
            return Tools::error('无队伍');
        }
    }

    public function check()
    {
        $number = request('number');
        $troops = Redis::get("troops:$number");

        if ($troops) {
            return Tools::success('队伍');
        } else {
            return Tools::error('队伍不存在');
        }
    }

    public function troopsList()
    {
//        $data = [];
//        $data['number'] = $this->sendTroopsNumber();
//        $data['user_id'] = $number;
//        $data['id'] = $this->sendTroopsId();
//        $data['cooperate_id'] = $firendNumber;
//        $data['created_at'] = date('Y-m-d H:i:s');
//        $data['updated_at'] = date('Y-m-d H:i:s');
//
//        $res = Redis::lpush('troops:list', serialize($data));
//
//        $troopsData = [];
//        $troopsData[$firendNumber] = unserialize(Redis::get('user:number:' . $firendNumber));
//        $troopsData[$number] = unserialize(Redis::get('user:number:' . $number));
//        $troopsData['troops'] = $data['number'];
//
//        Redis::set('troops:' . $data['number'], serialize($troopsData));
//        Redis::set('user:troops:number:' . $number, $data['number']);
//        Redis::set('user:troops:number:' . $firendNumber, $data['number']);

        $troops = [];

        for ($i = 1; $i < 500; $i++) {
            $troopsItem = Redis::get('troops:' . $i);
            if ($troopsItem) {
                $troopsItem = unserialize($troopsItem);
                foreach ($troopsItem as $key => $val) {
                    $item = [];
                    $troops[] = unserialize($troopsItem);
                }

            }
        }

        foreach ($troops as $key => $val) {
            $troops[$key]['user'] = unserialize(Redis::get('user:number:' . $troops[$key]['user_id']));
            $troops[$key]['cooperate'] = unserialize(Redis::get('user:number:' . $troops[$key]['cooperate_id']));
        }

        return Tools::setData($troops);
    }

    public function sendTroopsNumber()
    {
        if (Redis::exists('troops:number:id')) {
            Redis::incr('troops:number:id');
            return Redis::get('troops:number:id');
        } else {
            $number = Troops::max('number');
            ++$number;
            Redis::set('troops:number:id', $number);
            return $number;
        }
    }

    public function sendTroopsId()
    {
        $key = 'is:troops:id';
        if (Redis::exists($key)) {
            Redis::incr($key);
            return Redis::get($key);
        } else {
            $number = 30;
            ++$number;
            Redis::set($key, $number);
            return $number;
        }
    }

}
